/*
 * @Author: kanglang
 * @Date: 2020-10-29 14:38:11
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-08-12 14:00:46
 * @Description: 欢迎/引导页
 */

import React, { Component } from 'react';
import { StyleSheet, Image, SafeAreaView } from 'react-native';
import { msg, cache, AsyncStorage, SyncStorage } from '@/common';
import { px2dp, mainBgColorWhite, fontColorBlack } from '@/styles';
import { launch } from '@/images';
import api from '@/api';

export default class Welcome extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    // 去请求用户信息，看cookie失效没有
    this.getUserInfo();
    // 客服电话全局
    this.getCustomService();
  }

  render() {
    return (
      <SafeAreaView style={styles.container}>
        <Image style={styles.startLogo} source={launch} resizeMode='contain' />
        {/* <Text style={styles.cpCompany}>小&nbsp;马&nbsp;国&nbsp;炬&nbsp;&nbsp;循&nbsp;名&nbsp;而&nbsp;为</Text> */}
      </SafeAreaView>
    );
  }

  getUserInfo = () => {
    api.user.getUserInfo().then((res) => {
      if (res.success) {
        const Role = SyncStorage.getItem(cache.ROLE);
        this.goToRoleApp(Role);
      } else {
        this.clearStorage();
        msg.emit('router: reset', {
          routeName: 'LoginView',
        });
      }
    }).catch(() => {
      AsyncStorage.getItem(cache.ROLE).then((Role) => {
        console.log('🚀🚀🚀wimi======>>>111', Role);
        this.goToRoleApp(Role);
      });

      // this.clearStorage();
      // msg.emit('router: reset', {
      //   routeName: 'LoginView',
      // });
    });
  };

  // 清理掉原有的用户信息和角色信息
  clearStorage =() => {
    AsyncStorage.removeItem(cache.USER_INFO);
    AsyncStorage.removeItem(cache.ROLE);
  }

  // 角色判断，不同角色进入不同app
  goToRoleApp = (role) => {
    console.log('🚀🚀🚀wimi======>>>role', role);
    if (!role) {
      msg.emit('router: reset', {
        routeName: 'RoleSwitch',
      });
      return;
    }
    // 司机：driver  车主：car_owner  货主：goods_owner
    if (role === 'driver') {
      msg.emit('router: reset', {
        routeName: 'DriverTab',
      });
    } else if (role === 'car_owner') {
      msg.emit('router: reset', {
        routeName: 'CarOwnerTab',
      });
    } else if (role === 'goods_owner') {
      msg.emit('router: reset', {
        routeName: 'GoodsOwnerTab',
      });
    }
  };

   // 获取客服电话
   getCustomService = () => {
     const params = {
       code: 'ydxlmkfdh'
     };
     api.user.getConfigValue(params).then(res => {
       if (res.success) {
         const serviceNum = res.data.keys;
         AsyncStorage.setItem(cache.SERVICE_NUMBER, serviceNum);
       }
     });
   };
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: mainBgColorWhite,
  },
  startLogo: {
    flex: 1,
  },
  cpCompany: {
    height: px2dp(210),
    marginTop: px2dp(46),
    color: fontColorBlack,
    fontSize: px2dp(32),
  },
});
